home *** CD-ROM | disk | FTP | other *** search
- Path: inforamp.net!ts14-03
- From: rmorin@inforamp.net (Randy Charles Morin)
- Newsgroups: comp.lang.c++
- Subject: Re: Casting
- Date: Sat, 16 Mar 96 08:54:09 GMT
- Organization: MiddleWorld SoftWare
- Message-ID: <4idvk3$pc1@sam.inforamp.net>
- References: <3146DB9C.4022@cs.bham.ac.uk>
- NNTP-Posting-Host: ts14-03.tor.inforamp.net
- X-Newsreader: News Xpress Version 1.0 Beta #4
-
- In article <3146DB9C.4022@cs.bham.ac.uk>,
- Matthew G Butler <M.G.Butler-MSCSE95@cs.bham.ac.uk> wrote:
- >Can anyone tell me how to cast from one data type to another? What is
- >the syntax? Do I have to cast explicitly or can I stick a casting
- >function into my ADT and let the sprites sort it out.
-
- #1
- If you wan't to cast, say a void * to a int *, try the following.
-
- void * p;
- int * i;
- ..
- i = (int *)p;
-
- This is just an example.
-
- #2
- Another way of casting is by writing copy constructors.
-
- Example:
-
- class MyClass
- {
- public:
- MyClass();
- MyClass(int &i);
- int i;
- };
-
- MyClass::MyClass() {i=0};
- MyClass::MyClass(int &a) {i=a};
-
- #3
- Also you can write implicit casting routines. The following routine adds an
- integer to a MyClass without casting.
-
- class MyClass
- {
- public:
- int i;
- MyClass& operator+ (int&);
- };
-
- MyClass& MyClass::operator+ (int& a)
- {
- i += a;
- return *this;
- };
-
- I hope this is enough
-
- Agrivar
-